<?php
// +----------------------------------------------------------------------
// | 部门业务
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\model\SysDeptModel;
use app\common\service\SysDeptService as CommonSysDeptService;
use app\common\enum\BaseStatusEnum;
use app\common\enum\ErrorEnum;
use app\common\model\SysUserModel;

class SysDeptService {
    /**
     * 分页
     * @param  array  $param  请求参数
     * @return array
     */
    public static function list($params = []){
        $model = new SysDeptModel();
        if (isset($params['status']) && $params['status']) {
            $model = $model->where('status', $params['status']);
        } 
        $resList = $model->order('sort desc, id asc')->select()->toArray();
        if (empty($resList)) {
            return [];
        }
        $leaderIds = arrayColumn($resList, 'leader_id');
        if ($leaderIds) {
            $userMap = SysUserModel::where('id', 'in', $leaderIds)->column('realname', 'id');
        }
        
        foreach ($resList as $k => $v) {
            $resList[$k]['statusName'] = BaseStatusEnum::getDescription($v['status']);
            $resList[$k]['leaderName'] = isset($userMap) && isset($userMap[$v['leader_id']]) ? $userMap[$v['leader_id']] : '';
        }

        return treeData($resList);
    }

    /**
     * 查询某一列的值,并指定某一列为索引
     * @param  array  $param  请求参数
     * @return array
     */
    public static function selectColumnByIds($ids) {
        return SysDeptModel::where('id','in',$ids)->column('dept_name', 'id');
    }
   
    /**
     * 新增数据
     * @param  array  $data  新增的数据
     * @return json
     */
    public static function save($data){
        return CommonSysDeptService::save($data);
    }

    /**
     * 更新数据
     * @param  array  $data  更新的数据
     * @return json
     */
    public static function update($data){
        $info = SysDeptModel::find($data['id']);
        if(!$info){
            return failure(ErrorEnum::F_IS_NOT_EXIST_CODE, ErrorEnum::F_IS_NOT_EXIST_DESC);
        }

        $info->save($data);
        return $info->id;
    }

    /**
     * 详情
     * @param  array  $id  数据ID
     * @return json
     */
    public static function info($id){
        $data = CommonSysDeptService::info($id);
        if ($data['parent_id'] == 0) {
            $data['parent_dept_name'] = '一级部门';
        } else {
            $data['parent_dept_name'] = SysDeptModel::where('id', $data['parent_id'])->value('dept_name');
        }
        return $data;
    }

    /**
     * 删除
     * @param  string  $ids  数据ID
     * @return json
     */
    public static function destroy($ids){
        if(!empty($ids)){
            SysDeptModel::deleteById($ids);
        }
    }
}